package com.dfxy.blog.dao;

import com.dfxy.blog.entity.Approve;
import com.mysql.cj.util.StringUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Set;

public class ApproveDao {
    public Approve approve(Connection con, Approve approve) throws SQLException {
        if (con == null || approve == null || approve.getApproveUsername() == null) {
            return null;
        }

        String sql = "insert into approve values (?,?)";
        PreparedStatement pstat = con.prepareStatement(sql);
        pstat.setString(1, approve.getApproveUsername());
        pstat.setInt(2, approve.getBlogId());

        int approveResult = pstat.executeUpdate();
        if (approveResult > 0) {
            return approve;
        } else {
            return null;
        }
    }

    public Set<Integer> approveIdSet(Connection con, String username) throws SQLException {
        if (con == null || StringUtils.isEmptyOrWhitespaceOnly(username)) {
            return null;
        }

        String sql = "select blog_id from approve where approve_username = ?";
        PreparedStatement pstat = con.prepareStatement(sql);
        pstat.setString(1, username);
        ResultSet resultSet = pstat.executeQuery();

        Set<Integer> result = new HashSet<>();

        while (resultSet.next()) {
            result.add(resultSet.getInt("blog_id"));
        }

        return result;
    }

    public Set<String> approveUsernameSet(Connection con, int blogId) throws SQLException {
        if (con == null) {
            return null;
        }

        String sql = "select approve_username from approve where blog_id = ?";
        PreparedStatement pstat = con.prepareStatement(sql);
        pstat.setInt(1, blogId);
        ResultSet resultSet = pstat.executeQuery();

        Set<String> result = new HashSet<>();

        while (resultSet.next()) {
            result.add(resultSet.getString("approve_username"));
        }

        return result;
    }

    public int delete(Connection con, Approve approve) throws SQLException {
        if (con == null || approve == null
                || StringUtils.isEmptyOrWhitespaceOnly(approve.getApproveUsername())
        ) {
            return -1;
        }

        String sql = "delete from approve where approve_username = ? and blog_id = ?";
        PreparedStatement pstat = con.prepareStatement(sql);
        pstat.setString(1, approve.getApproveUsername());
        pstat.setInt(2, approve.getBlogId());

        int updateResult = pstat.executeUpdate();
        if (updateResult > 0) {
            return updateResult;
        } else {
            return -1;
        }
    }
}
